const { fileTypeError, fileUploadError, publishGoodsError, invalidGoodsID } = require("../consisitant/err.type")
const { createGoods, updateGoods, removeGoods, restoreGoods, findGoods } = require("../service/goods.service")

class GoodsController {
    async upload(ctx, next) {
        try {
            let file = ctx.request.files
            const fileType = ['image/jpeg']
            if (!fileType.includes(file.mimetype)) {
                ctx.app.emit('error', fileTypeError, ctx)
                return
            }
            ctx.body = {
                code: 0,
                message: "上传文件成功",
                result: ""
            }
        } catch (err) {
            ctx.emit('error', fileUploadError, ctx)
        }
    }
    async create(ctx, next) {
        try {
            const res = await createGoods(ctx.request.body)
            ctx.body = {
                code: 0,
                message: '发布商品成功',
                result: res
            }
        } catch (err) {
            return ctx.emit('error', publishGoodsError, ctx)
        }
    }
    async update(ctx, next) {
        try {
            const res = await updateGoods(ctx.params.id, ctx.request.body)
            if (res) {
                ctx.body = {
                    code: 0,
                    message: '商品修改成功'
                }
            } else {
                return ctx.app.emit('error', invalidGoodsID, ctx)
            }
        } catch (err) {
            console.error(err)
        }
    }
    async remove(ctx, next) {
        try {
            const res = await removeGoods(ctx.params.id)
            if (res) {
                ctx.body = {
                    code: 0,
                    message: '下架商品成功'
                }
            } else {
                return ctx.app.emit('error', invalidGoodsID, ctx)
            }
        } catch (err) {
            console.error(err)
        }
    }
    async restore(ctx, next) {
        try {
            const res = await restoreGoods(ctx.params.id)
            if (res) {
                ctx.body = {
                    code: 0,
                    message: '上架商品成功'
                }
            } else {
                return ctx.app.emit('error', invalidGoodsID, ctx)
            }
        } catch (err) {
            console.error(err)
        }
    }
    async findAll(ctx) {
        const { pageNum = 1, pageSize = 10 } = ctx.request.query
        const res = await findGoods(pageNum, pageSize)
        ctx.body = {
            code: 0,
            message: '获取商品列表成功',
            result: res
        }
    }
}

module.exports = new GoodsController()